package com.wzdigit.wms.wms.service.core.inventory;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.GoodsIsHoldEnum;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.request.report.GoodsSnReportSearchRequest;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.client.response.report.GoodsSnReportReponse;
import com.wzdigit.wms.basic.client.response.report.ScanSnResponse;
import com.wzdigit.wms.basic.domain.inventory.GoodsHis;
import com.wzdigit.wms.basic.enums.GdnTypeEnum;
import com.wzdigit.wms.basic.enums.GoodsStatusEnum;
import com.wzdigit.wms.basic.enums.InvAttrEnum;
import com.wzdigit.wms.basic.enums.QaStatusEnum;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsHisMapper;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsMapper;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsSnReportMapper;
import com.wzdigit.wms.common.entity.ExcelExportConfig;
import com.wzdigit.wms.common.utils.HttpExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 条码查询报表Service&PDA扫描条码
 * Created by zyf on 2021/5/22 9:13
 */
@Service
@Slf4j
public class GoodsSnReportService {
    @Autowired
    private GoodsSnReportMapper goodsSnReportMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsHisMapper goodsHisMapper;

    //默认货主
    @Value(value = "${default_owner.name}")
    private String DEFAULT_OWNER_NAME;

    //去除空格
    private void filterSpace(GoodsSnReportSearchRequest search){
        if (search.getFilter()!=null){
            search.setFilter(search.getFilter().replace(" ",""));
        }
        if (search.getGdnNo()!=null){
            search.setGdnNo(search.getGdnNo().replace(" ",""));
        }
        if (search.getSourceShipNotice()!=null){
            search.setSourceShipNotice(search.getSourceShipNotice().replace(" ",""));
        }
        if (search.getSkuCode()!=null){
            search.setSkuCode(search.getSkuCode().replace(" ",""));
        }
        if (search.getCntrNo()!=null){
            search.setCntrNo(search.getCntrNo().replace(" ",""));
        }
        if (search.getWhsCode()!=null){
            search.setWhsCode(search.getWhsCode().replace(" ",""));
        }
    }

    //查询条码报表【复用】
    public List<GoodsSnReportReponse> selectGoodsSn(GoodsSnReportSearchRequest search){
        //根据前端传的long毫秒值设置时间
        if (search.getBeginTime()!=null){
            search.setBeginTimeDate(new Date(search.getBeginTime()));
        }
        if (search.getEndTime()!=null){
            search.setEndTimeDate(new Date(search.getEndTime()));
        }

        //查询字段去除空格
        this.filterSpace(search);

        List<GoodsSnReportReponse> results = goodsSnReportMapper.selectAll(search);

        //设置类型
        for (GoodsSnReportReponse result : results) {
            GdnTypeEnum gdnTypeEnum = GdnTypeEnum.getEnumByCode(result.getGdnType());
            if (gdnTypeEnum!=null){
                result.setReturnGdnType(gdnTypeEnum.enumName);
            }
        }

        return results;
    }

    //分页查询条码报表
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<GoodsSnReportReponse>> searchGoodsSnReport(
            GoodsSnReportSearchRequest search, Pager<?> pager){
        Page<GoodsSnReportReponse> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        List<GoodsSnReportReponse> datas = this.selectGoodsSn(search);
        PagerInfo<List<GoodsSnReportReponse>> pagerInfo = new PagerInfo<>();
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //导出订单流水报表信息
    @Transactional
    public void exportGoodsSnReport(
            GoodsSnReportSearchRequest search,
            HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws Exception{
        ServletOutputStream out = null;
        XSSFWorkbook workbook = null;
        try {
            List<GoodsSnReportReponse> resultDatas = this.selectGoodsSn(search);
            List<ExcelExportConfig> configs = new ArrayList<>();
            configs.add(new ExcelExportConfig("发货单号", "gdnNo", 120));
            configs.add(new ExcelExportConfig("类型", "returnGdnType", 120));
            configs.add(new ExcelExportConfig("条码", "goodsSn", 120));
            configs.add(new ExcelExportConfig("客户条码", "customerSn", 120));
            configs.add(new ExcelExportConfig("发货通知单", "sourceShipNotice", 120));
            configs.add(new ExcelExportConfig("柜号", "cntrNo", 120));
            configs.add(new ExcelExportConfig("封条号", "sealNo", 120));
            configs.add(new ExcelExportConfig("物料编码", "skuCode", 120));
            configs.add(new ExcelExportConfig("物料名称", "descCn", 120));
            configs.add(new ExcelExportConfig("仓库编码", "whsCode", 120));
            configs.add(new ExcelExportConfig("仓库名称", "whsName", 120));
            configs.add(new ExcelExportConfig("年月", "yearAndMonth", 120));
            configs.add(new ExcelExportConfig("数量", "qty", 120));
            configs.add(new ExcelExportConfig("扫描人", "createUser", 120));
            configs.add(new ExcelExportConfig("装柜时间", "createTime", 120));
            workbook = HttpExcel.newListToExcel(resultDatas, configs);
            String userAgent = servletRequest.getHeader("USER-AGENT");
            String fileName = "条码查询报表";
            if (userAgent.contains("Mozilla")) {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "utf8");
            }
            servletResponse.setContentType("application/octet-stream");
            servletResponse.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xlsx");
            servletResponse.flushBuffer();
            out = servletResponse.getOutputStream();
            workbook.write(out);
        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
            if(workbook != null) {
                workbook.close();
            }
        }

    }


    //PDA扫描SN获取信息
    @Transactional
    public Result<ScanSnResponse> scanSnInfo(String goodsSn){
        if (goodsSn==null){
            Shift.fatal("请扫描条码!");
        }
        ScanSnResponse result = goodsMapper.selectSnInfo(goodsSn);
        if (result!=null){
            //设置返回结果
            if (result.getQaStatus()!=null){
                QaStatusEnum qaStatusEnum = QaStatusEnum.getEnumByCode(result.getQaStatus());
                if (qaStatusEnum!=null){
                    result.setQaStatusString(qaStatusEnum.enumName);
                }
            }
            if (result.getIsHold()!=null){
                GoodsIsHoldEnum isHoldEnum = GoodsIsHoldEnum.getEnumByCode(result.getIsHold());
                if (isHoldEnum!=null){
                    result.setIsHoldString(isHoldEnum.enumName);
                }
            }
            if (result.getStatus()!=null){
                GoodsStatusEnum statusEnum = GoodsStatusEnum.getEnumByCode(result.getStatus());
                if (statusEnum!=null){
                    result.setStatusString(statusEnum.enumName);
                }
            }
            result.setOwner(DEFAULT_OWNER_NAME);
            return new Result<>(true,"扫描成功",result);
        }
        //WMS_GOODS表找不到去WMS_GOODS_HIS表查询
        QueryWrapper<GoodsHis> goodsHisQueryWrapper=new QueryWrapper<>();
        goodsHisQueryWrapper.eq("GOODS_SN", goodsSn);
        result= goodsMapper.selectSnHisInfo(goodsSn);
        if (result==null){
            Shift.fatal("扫描条码["+goodsSn+"]不存在，请扫描正确的条码!");
        }
        //设置返回结果
        if (result.getQaStatus()!=null){
            QaStatusEnum qaStatusEnum = QaStatusEnum.getEnumByCode(result.getQaStatus());
            if (qaStatusEnum!=null){
                result.setQaStatusString(qaStatusEnum.enumName);
            }
        }
        if (result.getIsHold()!=null){
            GoodsIsHoldEnum isHoldEnum = GoodsIsHoldEnum.getEnumByCode(result.getIsHold());
            if (isHoldEnum!=null){
                result.setIsHoldString(isHoldEnum.enumName);
            }
        }
        if (result.getStatus()!=null){
            GoodsStatusEnum statusEnum = GoodsStatusEnum.getEnumByCode(result.getStatus());
            if (statusEnum!=null){
                result.setStatusString(statusEnum.enumName);
            }
        }
        result.setOwner(DEFAULT_OWNER_NAME);
        return new Result<>(true,"扫描成功",result);
    }

}
